package cn.edu.klmy.controller;

import cn.edu.klmy.dao.ITextbookDao;
import cn.edu.klmy.models.course.Textbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import web.models.CommonResult;
import web.models.Page;
import web.util.RequestUtil;

import javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping("/textbook")
public class TextbookController {

    @Resource(name = "textbookDao")
    private ITextbookDao textbookDao;

    @RequestMapping("/add")
    @ResponseBody
    public CommonResult addTextbook(@ModelAttribute Textbook textbook) {
        textbookDao.addTextbook(textbook);
        return new CommonResult(new Boolean(true));
    }

    @RequestMapping("/update")
    @ResponseBody
    public CommonResult updateTextbook(@ModelAttribute Textbook textbook) {
        textbookDao.updateTextbook(textbook);
        return new CommonResult(new Boolean(true));
    }

    @RequestMapping("/remove")
    @ResponseBody
    public CommonResult removeTextbook(@RequestParam int textbookId) {
        textbookDao.removeTextbook("ID", textbookId);
        return new CommonResult(new Boolean(true));
    }

    @RequestMapping("/exists")
    @ResponseBody
    public CommonResult textbookExists(@RequestParam String textbookName) {
        boolean result = textbookDao.textbookExists(textbookName);
        return new CommonResult(result);
    }

    @RequestMapping("/all")
    @ResponseBody
    public Page<Textbook> getTextbooksPage(@RequestParam int page, @RequestParam int rows) {
        List<Textbook> textbooks = textbookDao.getTextbooks(null, page, rows);
        int count = textbookDao.getTextbookCount(null);
        return new Page<Textbook>(count, textbooks);
    }

    @RequestMapping("/in-courses/{courseId}")
    @ResponseBody
    public List<Textbook> getTextbooksInCourse(@PathVariable int courseId) {
        return textbookDao.getTextbooks("TEXTBOOK.COURSE_ID", courseId);
    }

    public void setTextbookDao(ITextbookDao textbookDao) {
        this.textbookDao = textbookDao;
    }
}
